<?php namespace App\Admin\Base;

require_once app_path().'/Library/excel/PHPExcel.php';

trait XmlService {
    
    private $uid = 0;
    
    public function createXml(){
        $fileName = '网大.xlsx';
        $folderName = '网大';
        $data = $this->getData(base_path().'/'.$fileName);
        $dir = base_path().'/'.$folderName;
        array_shift($data);
        foreach($data as $item){
            $newFile = $dir.'/'.$item['A'].'_'.str_pad($item['D'], 2, '0', STR_PAD_LEFT).'.xml';
            file_put_contents($newFile, $this->getXML($item));
            $this->fxml($newFile);
        }
        echo '创建成功';
    }
    
    private function getXML($item){
        $content = '<?xml version="1.0" encoding="utf-8"?>'."\r\n";
        $content .= '<ADI>'."\r\n";
        //数据
        $assetName = $item['A'];
        $typeArr = preg_split('/( +)|(\/)/', trim($item['B']));
        $type = isset($typeArr[0]) ? $typeArr[0] : '';
        $chapter = $item['C'];
        $episodeID = $item['D'];
        $runTime = intval($item['E']);
        if(substr_count($runTime, ':') < 1 && $runTime >= 60){
            if($runTime >= 3600){
                $runTime = floor($runTime/3600).':'.floor(($runTime%3600)/60).':'.($runTime%60);
            }else if($runTime >= 60){
                $runTime = floor($runTime/60).':'.($runTime%60);
            }
        }
        if(substr_count($runTime, ':') == 0){
            $runTime = '00:00:'.(strlen($runTime) > 1 ? $runTime : '0'.$runTime);
        }elseif(substr_count($runTime, ':') == 1){
            $runTimeArr = explode(':', $runTime);
            $runTime = '00:'.(strlen($runTimeArr[0]) > 1 ? $runTimeArr[0] : '0'.$runTimeArr[0]).':'.(strlen($runTimeArr[1]) > 1 ? $runTimeArr[1] : '0'.$runTimeArr[1]);
        }else{
            $runTime = strlen($runTime) > 1 ? $runTime : '0'.$runTime;
        }
        $videoName = $item['F'];
        $year = $item['G'];
        $country = $item['H'];
        $captionLanguage = $item['I'];
        $audioLanguage = $item['J'];
        $summaryLong = $item['K'];
        $summaryShort = $item['L'];
        $director = $this->fsplit($item['M']);
        $actors = $this->fsplit($item['N']);
        $time = date('Y-m-d H:i:s', strtotime($item['O']));
        $provider = str_replace('彩云之端', 'CYZD', $item['P']);
        $assetId = $item['Q'];
        $uniqueId = str_replace('彩云之端', 'CYZD', $item['R']);
        $licensingWindowStart = date('Y-m-d H:i:s', strtotime($item['S']));
        $licensingWindowEnd = date('Y-m-d H:i:s', strtotime($item['T']));
        $episodeName = $assetName;
        $category = $this->fsplit($item['B']);
        $videoUrl = $videoName.'.mp4';
        $posterUrl = $videoName.'.jpg';
        $providerId = '123456';

        //<Metadata>
        $content .= '<Metadata>'."\r\n";
        $content .= '<AMS ';
        $content .= 'Provider="'.$provider.'" ';
        $content .= 'Product="MOD" ';
        $content .= 'Asset_Name="'.$assetName.'" ';
        $content .= 'Version_Major="1" ';
        $content .= 'Version_Minor="0" ';
        $content .= 'Description="Asset_Package" ';
        $content .= 'Creation_Date="'.$time.'" ';
        $content .= 'Provider_ID="'.$providerId.'" ';
        $content .= 'Asset_ID="'.$this->getUid().'" ';
        $content .= 'Asset_Class="package"';
        $content .= '/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Metadata_Spec_Version" Value="CableLabsVOD1.1"/>'."\r\n";
        $content .= '</Metadata>'."\r\n";
        //<Asset>
        $content .= '<Asset>'."\r\n";
        $content .= '<Metadata>'."\r\n";
        $content .= '<AMS ';
        $content .= 'Provider="'.$provider.'" ';
        $content .= 'Product="MOD" ';
        $content .= 'Asset_Name="'.$assetName.'" ';
        $content .= 'Version_Major="1" ';
        $content .= 'Version_Minor="0" ';
        $content .= 'Description="Asset_Package" ';
        $content .= 'Creation_Date="'.$time.'" ';
        $content .= 'Provider_ID="'.$providerId.'" ';
        $content .= 'Asset_ID="'.$this->getUid().'" ';
        $content .= 'Asset_Class="title" ';
        $content .= '/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Title" Value="'.$videoName.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Genre" Value="'.$type.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Run_Time" Value="'.$runTime.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Chapter" Value="'.$chapter.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Director" Value="'.$director .'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Actors" Value="'.$actors.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Summary_Long" Value="'.$summaryLong.'"/>'."\r\n"; 
        $content .= '<App_Data App="MOD" Name="Country" Value="'.$country.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Year" Value="'.$year.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Caption_Language" Value="'.$captionLanguage.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Audio_Language" Value="'.$audioLanguage.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Summary_Short" Value="'.$summaryShort.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Category" Value="'.$category.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Episode_Name" Value="'.$episodeName.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Episode_ID" Value="'.$episodeID.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Licensing_Window_Start" Value="'.$licensingWindowStart.'"/>'."\r\n";
        $content .= '<App_Data App="MOD" Name="Licensing_Window_End" Value="'.$licensingWindowEnd.'"/>'."\r\n";
        $content .= '</Metadata>'."\r\n";
        //视频
        $content .= '<Asset>'."\r\n";
        $content .= '<Metadata>'."\r\n";
        $content .= '<AMS ';
        $content .= 'Provider="'.$provider.'" ';
        $content .= 'Product="MOD" ';
        $content .= 'Asset_Name="'.$assetName.'" ';
        $content .= 'Version_Major="1" ';
        $content .= 'Version_Minor="0" ';
        $content .= 'Description="Asset_Package" ';
        $content .= 'Creation_Date="'.$time.'" ';
        $content .= 'Provider_ID="'.$providerId.'" ';
        $content .= 'Asset_ID="'.$this->getUid().'" ';
        $content .= 'Asset_Class="movie"';
        $content .= '/>'."\r\n";
        $content .= '</Metadata>'."\r\n";
        $content .= '<Content Value="'.$videoUrl.'"/>'."\r\n";
        $content .= '</Asset>'."\r\n";
        //海报
        $content .= '<Asset>'."\r\n";
        $content .= '<Metadata>'."\r\n";
        $content .= '<AMS ';
        $content .= 'Provider="'.$provider.'" ';
        $content .= 'Product="MOD" ';
        $content .= 'Asset_Name="'.$assetName.'" ';
        $content .= 'Version_Major="1" ';
        $content .= 'Version_Minor="0" ';
        $content .= 'Description="Asset_Package" ';
        $content .= 'Creation_Date="'.$time.'" ';
        $content .= 'Provider_ID="'.$providerId.'" ';
        $content .= 'Asset_ID="'.$this->getUid().'" ';
        $content .= 'Asset_Class="poster"';
        $content .= '/>'."\r\n";
        $content .= '</Metadata>'."\r\n";
        $content .= '<Content Value="'.$posterUrl.'"/>'."\r\n";
        $content .= '</Asset>'."\r\n";
        $content .= '</Asset>'."\r\n";
        $content .= '</ADI>'."\r\n";
        return $content;
    }

    private function getData($filePath){
        /**默认用excel2007读取excel，若格式不对，则用之前的版本进行读取*/
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)){
                return $this->inputError('文件格式不支持');
            }
        }
        $PHPExcel = $PHPReader->load($filePath);
        $data = [];
        $sheets = $PHPExcel->getAllSheets();
        foreach($sheets as $sheet){
            $data = $this->getInfoFromSheet($sheet);
        }
        return $data;
    }
    
    private function getInfoFromSheet($sheet){
        //列号
        $colNamesStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $colNames = [];
        for($i=0;$i<4;$i++){
            for($j=0;$j<strlen($colNamesStr);$j++){
                $colNames[] = ($i ? $colNamesStr[$i-1] : '').$colNamesStr[$j];
            }
        }
        $columnCount = 0;
        for($i = 0;$i<= 100; $i++){
            $val = trim($sheet->getCell($colNames[$i].'1')->getValue());
            if(strlen($val) == 0){
                break;
            }
            $columnCount = $i;
        }
        $data = [];
        $rowCount = $sheet->getHighestRow();
        for($row = 1;$row <= $rowCount;$row++){
            $item = [];
            $isEmpty = true;
            for($column = 0;$column<= $columnCount; $column++){
                $cell = $sheet->getCell($colNames[$column].$row);
                $val = $cell->getFormattedValue();
                $item[$colNames[$column]] = $val;
                if(strlen($val) > 0){
                    $isEmpty = false;
                }
            }
            if(!$isEmpty){
                $data[] = $item;
            }
        }
        return $data;
    }
    
    private function getUid(){
        $this->uid += 1;
        return 'cyzdf'.time(). str_pad($this->uid, 6, '0', STR_PAD_LEFT);
    }
    
    private function fsplit($target){
        return preg_replace('/( +)|(\/)/', '|', trim($target));
    }
    
    private function fxml($name){
        $fp = fopen($name, 'r+');
        $content = '';
        $n = 0;
        $i = 0;
        while($line = fgets($fp)){
            $i++;
            if($i<2){
                $content .= $line;
                continue;
            }
            if(preg_match('/<[^\/]*>/', $line)){//开始标签
                $content .= str_repeat('    ', $n).$line;
                $n++;
            }else if(preg_match('/<\/.*?>/', $line)){//结束标签
                $n--;
                $content .= str_repeat('    ', $n).$line;
            }else{
                $content .= str_repeat('    ', $n).$line;
            }
        }
        fclose($fp);
        file_put_contents($name, $content);
    }
}